<template>
    <VZPanel title="市场不良率" simple iconText="mdi-chart-pie">
      <div style="margin:-16px">
        <v-card>
          <v-row>
            <!-- 搜索零件简称 -->
            <v-col cols="3">
              <v-autocomplete
                v-model="selectedReferred"
                :items="referredItems"
                item-text="text"
                item-value="id"
                label="搜索零件简称"
                outlined
                dense
                clearable
                :filter="customFilter"
                :loading="loading"
                multiple
              ></v-autocomplete>
            </v-col>
  
            <!-- 搜索产品 -->
            <v-col cols="3">
              <v-autocomplete
                v-model="selectedMaterial"
                :items="materialItems"
                item-text="text"
                item-value="id"
                label="搜索产品"
                outlined
                dense
                clearable
                :filter="customFilter"
                :loading="loading"
                multiple
              ></v-autocomplete>
            </v-col>
  
            <!-- 起始日期 -->
            <v-col cols="2">
              <v-menu
                ref="startMenu"
                v-model="startMenu"
                :close-on-content-click="false"
                max-width="290"
                min-width="290"
                offset-y
              >
                <template v-slot:activator="{ on, attrs }">
                  <v-text-field
                    v-model="startYear"
                    label="起始日期"
                    readonly
                    v-bind="attrs"
                    v-on="on"
                    outlined
                    dense
                  ></v-text-field>
                </template>
                <v-date-picker
                  v-model="startYear"
                  type="month"
                  @change="startMenu = false"
                  :max="endYear"
                  locale="zh-cn"
                  :allowed-dates="allowedDates"
                ></v-date-picker>
              </v-menu>
            </v-col>
  
            <!-- 结束日期 -->
            <v-col cols="2">
              <v-menu
                ref="endMenu"
                v-model="endMenu"
                :close-on-content-click="false"
                max-width="290"
                min-width="290"
                offset-y
              >
                <template v-slot:activator="{ on, attrs }">
                  <v-text-field
                    v-model="endYear"
                    label="结束日期"
                    readonly
                    v-bind="attrs"
                    v-on="on"
                    outlined
                    dense
                  ></v-text-field>
                </template>
                <v-date-picker
                  v-model="endYear"
                  type="month"
                  @change="endMenu = false"
                  :min="startYear"
                  locale="zh-cn"
                  :allowed-dates="allowedDates"
                ></v-date-picker>
              </v-menu>
            </v-col>
  
            <!-- 导出按钮 -->
            <v-col cols="auto" class="d-flex align-center" style="margin-left: 30px;">
              <v-tooltip bottom>
                <template v-slot:activator="{ on, attrs }">
                  <v-btn
                    icon
                    color="success"
                    @click="exportToCSV"
                    :disabled="loading"
                    class="mr-2"
                    v-bind="attrs"
                    v-on="on"
                    style="width: 36px; height: 36px"
                  >
                    <v-icon size="24">mdi-file-excel</v-icon>
                  </v-btn>
                </template>
                <span>导出Excel</span>
              </v-tooltip>
              <!-- <v-tooltip bottom>
                <template v-slot:activator="{ on, attrs }">
                  <v-btn
                    icon
                    color="primary"
                    @click="exportChart"
                    :disabled="loading"
                    v-bind="attrs"
                    v-on="on"
                    style="width: 36px; height: 36px"
                  >
                    <v-icon size="24">mdi-image</v-icon>
                  </v-btn>
                </template>
                <span>导出图片</span>
              </v-tooltip> -->
            </v-col>
          </v-row>
  
          <!-- 故障率表格 -->
          <v-row class="mt-2">
            <v-col cols="12">
              <v-card class="pa-2" style="padding-bottom: 20px!important;">
                <div class="text-subtitle-1 mb-2">故障率图表</div>
                <v-simple-table dense class="excel-style-table" ref="table" style="border: 2px solid black;">
                  <thead>
                    <tr style="border-bottom: 2px solid black;border-color: black!important;">
                      <td rowspan="3" style="vertical-align: middle; border-bottom: thin solid black;text-align:center; border-right: thin solid black; ">年份</td>
                      <template v-for="(year, index) in years" :key="year">
                        <th :colspan="getYearSpan(year)" :style="{ 'border-bottom': 'thin solid black','text-align':'center', borderRight: index < years.length - 1 ? '2px solid black' : '' }">
                          {{ year }}
                        </th>
                      </template>
                    </tr>
                  </thead>
                  <tbody>
                    <tr style="border-bottom: 2px solid black;">
                      <td style="vertical-align: middle; border-bottom: thin solid black;text-align:center; border-right: thin solid black; " >月份</td>
                      <template v-for="(year, yearIndex) in years" :key="yearIndex">
                        <td v-for="month in getMonths([year]) || []" :key="month">{{ month || '' }}</td>
                      </template>
                    </tr>
                    <tr>
                      <td style="vertical-align: middle; border-bottom: thin solid black;text-align:center; border-right: thin solid black; ">故障数</td>
                      <td v-for="(item, index) in tableItems || []" :key="index">{{ item.num || '0' }}</td>
                    </tr>
                    <tr>
                      <td style="vertical-align: middle; border-bottom: thin solid black;text-align:center; border-right: thin solid black; ">发货数</td>
                      <td v-for="(item, index) in tableSendItems || []" :key="index">{{ item.sendnum || '' }}</td>
                    </tr>
                    <tr>
                      <td style="vertical-align: middle; border-bottom: thin solid black;text-align:center; border-right: thin solid black; ">故障率</td>
                      <td v-for="(item, index) in tableItemsRate || []" :key="index">{{ item.faultRate || '' }}</td>
                    </tr>
                    <tr>
                      <td style="vertical-align: middle; border-bottom: thin solid black;text-align:center; border-right: thin solid black; ">平均率</td>
                      <td width="290">{{ this.sumRate }}</td>
                    </tr>
                  </tbody>
                </v-simple-table>
              </v-card>
            </v-col>
          </v-row>
        </v-card>
      </div>
    </VZPanel>
  </template>
  
  <style scoped>
  .v-data-table{
    line-height: 2;
  }
  .v-application .pa-2{
    padding-bottom: 20px!important;
  }
  /* 确保页面高度为100% */
  html, body {
  height: 100%;
  margin: 0;
  }
  /* 容器高度占满页面 */
  .full-height-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}
/* 卡片高度占满剩余空间 */
.full-height-card {
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 表格容器高度 */
.table-container {
  flex: 1;
  overflow-y: auto; /* 内部滚动 */
}
/* 表格卡片高度 */
.table-card {
  flex: 2;
  display: flex;
  flex-direction: column;
}
  /* 自定义表格样式 */
  .excel-style-table {
    border: 2px solid black; /* 添加外边框 */
    border-collapse: separate; /* 避免边框合并 */
    border-spacing: 0; /* 移除单元格间距 */
    
  }
  .excel-style-table th,
  .excel-style-table td {
    border: 1px solid black; /* 添加细边框 */
    padding: 4px 8px; /* 减小内边距，使表格更紧凑 */
    text-align: center; /* 内容居中对齐 */
  }
  
  .excel-style-table th {
    background-color: #f5f5f5; /* 表头背景色 */
    font-weight: bold; /* 加粗字体 */
  }
  
  .excel-style-table tbody tr:nth-child(even) {
    background-color: #fafafa; /* 偶数行背景色 */
  }
  
  /* 确保列分隔线不间断 */
  .excel-style-table td + td {
    border-left: 2px solid black !important; /* 强制应用分隔线 */
  }
  </style>
  
  <script>
  export default {
    data() {
      return {
        nameList: [],
        numList: [],
        nameSendList: [],
        numSendList: [],
        sql: "SELECT DATE_FORMAT(back_month, '%m') AS `name`,COUNT(*) AS num " +
             "FROM tt_sale_record_qms a " +
             "WHERE DATE_FORMAT(back_month, '%Y') >= '2023' " +
             "GROUP BY DATE_FORMAT(back_month, '%m') ORDER BY `name`; ",
        materialSql: "SELECT id,CONCAT(ASSEMBLY_CODE,'   ',name) name FROM tb_standard_assembly_product WHERE MARK_FOR_DELETE = 0",
        referredSql: "SELECT c.id,CONCAT(c.SIMPLE_CALL,'   ',c.CODE) name FROM tt_sale_record_qms a " +
                     "LEFT JOIN tb_standard_assembly_product b ON a.MATERIAL_ID = b.ID " +
                     "LEFT JOIN tb_standard_assembly_product_referred c ON c.id = b.REFERRED_ID " +
                     "WHERE c.SIMPLE_CALL IS NOT NULL GROUP BY c.ID ",
        materialItems: [],
        referredItems: [],
        searchMaterial: '',
        selectedMaterial: '',
        selectedMaterialSend: '',
        selectedReferred: [],
        selectedReferredSend: [],
        yearOptions: [],
        startYear: '',
        endYear: '',
        startMenu: false,
        endMenu: false,
        loading: true,
        yearData: {},
        materialIds: [],
        materialCodes: [],
        tableHeaders: [],
        tableItems: [],
        tableSendItems: [],
        tableItemsRate: [],
        sumRate: '',
      };
    },
    computed: {
      years() {
        if (!this.startYear || !this.endYear) return [];
        const start = parseInt(this.startYear);
        const end = parseInt(this.endYear);
        return Array.from({ length: end - start + 1 }, (_, i) => String(start + i));
      },
    },
    methods: {
      allowedDates(val) {
        return true; // 允许选择所有日期
      },
      search_data() {
        if (!this.materialIds.length > 0 || !this.materialIds) return;
        this.loading = true;
        if (!Array.isArray(this.materialIds)) {
            return;
        }
        const params = {
            SQL: `SELECT DATE_FORMAT(MADE_TIME, '%Y-%m') AS name, COUNT(*) AS num 
                FROM tt_sale_record_qms a 
                WHERE a.MATERIAL_ID in (${this.materialIds.join(',')}+' ')
                AND MADE_TIME IS NOT NULL
                AND DATE_FORMAT(MADE_TIME, '%Y-%m') != ''
                AND (DATE_FORMAT(MADE_TIME, '%Y-%m') >= '${this.startYear}' AND DATE_FORMAT(MADE_TIME, '%Y-%m') <= '${this.endYear}') 
                GROUP BY DATE_FORMAT(MADE_TIME, '%Y-%m') 
                ORDER BY DATE_FORMAT(MADE_TIME, '%Y-%m');`
        };
        app.utils.ajaxRequest({
            hideMsg: true,
            hideMask: true,
            url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
            params: { functionParam: JSON.stringify(params) },
            callBack: (res) => {
            if (res.success) {
                this.nameList = res.rows.map((item) => item.name);
                this.numList = res.rows.map((item) => item.num);
                this.updateTableData();
            }
            this.loading = false;
            },
        });
        },
      search_data_sendout() {
        if (this.materialCodes.length === 0) return;
        this.loading = true;
        if (!Array.isArray(this.materialCodes)) {
          console.error('materialCodes 不是一个数组');
          return;
        }
  
        // 格式化 materialCodes 并赋值给 this.formattedString
        this.formattedString = this.materialCodes.map(code => `'${code}'`).join(',');
  
        const params = {
          SQL: `SELECT CASE WHEN YEAR_MONTHS IS NULL THEN ' ' ELSE DATE_FORMAT(YEAR_MONTHS, '%Y-%m') END AS name, SUM(SHIPPED_QTY) AS sendNum 
                FROM TB_PART_SENDOUT a 
                WHERE a.MATNR in (${this.formattedString}) 
                AND (YEAR_MONTHS IS NULL OR (DATE_FORMAT(YEAR_MONTHS, '%Y-%m') >= '${this.startYear}' AND DATE_FORMAT(YEAR_MONTHS, '%Y-%m') <= '${this.endYear}')) 
                GROUP BY CASE WHEN YEAR_MONTHS IS NULL THEN '无日期' ELSE DATE_FORMAT(YEAR_MONTHS, '%Y-%m') END 
                ORDER BY CASE WHEN name = '无日期' THEN 1 ELSE 0 END, name;`,
        };
  
        app.utils.ajaxRequest({
          hideMsg: true,
          hideMask: true,
          url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
          params: { functionParam: JSON.stringify(params) },
          callBack: (res) => {
            if (res.success) {
              this.nameSendList = res.rows.map((item) => item.name);
              this.numSendList = res.rows.map((item) => item.sendnum);
              this.updateTableSendData();
            }
            this.loading = false;
          },
        });
      },
      async selectedReferredById() {
        if (this.selectedReferred.length) {
          this.selectedMaterial = '';
          await this.loadMaterialIdsByReferred();
          if (this.materialIds.length > 0) this.search_data();
        } else {
          if (!this.selectedMaterial) this.materialIds = [];
        }
      },
      async selectedReferredByCode() {
        if (this.selectedReferred.length) {
          this.selectedMaterial = '';
          await this.loadMaterialCodesByReferred();
          if (this.materialCodes.length > 0) this.search_data_sendout();
        } else {
          if (!this.selectedMaterial) this.materialIds = [];
        }
      },
      async selectedMaterialByCode() {
        if (this.selectedMaterial.length) {
          this.selectedReferred = '';
          await this.loadCodesByMaterialId();
          if (this.materialCodes.length > 0) this.search_data_sendout();
        } else {
          if (!this.selectedMaterial) this.materialIds = [];
        }
      },
      loadReferredData() {
        this.referredItems = [];
        const params = { SQL: this.referredSql };
        app.utils.ajaxRequest({
          hideMsg: true,
          hideMask: true,
          url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
          params: { functionParam: JSON.stringify(params) },
          callBack: (res) => {
            if (res.success && res.rows.length > 0) {
              this.referredItems = res.rows.map((item) => ({ text: item.name, id: item.id }));
              if (this.referredItems.length > 0) {
                this.loadMaterialIdsByReferred().then(() => {
                  if (this.materialIds.length > 0) this.search_data();
                });
                this.loadMaterialCodesByReferred().then(() => {
                  if (this.materialCodes.length > 0) this.search_data_sendout();
                  
                });
              }
            }
          },
        });
      },
      loadMaterialData() {
        this.materialItems = [];
        const params = { SQL: this.materialSql };
        
        app.utils.ajaxRequest({
          hideMsg: true,
          hideMask: true,
          url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
          params: { functionParam: JSON.stringify(params) },
          callBack: (res) => {
            if (res.success && res.rows.length > 0) {
              this.materialItems = res.rows.map((item) => ({ text: item.name, id: item.id ,code: item.code}));
            }
            this.loading = false;
          },
        });
      },
      loadMaterialIdsByReferred() {
        if (!this.selectedReferred.length) {
          this.materialIds = this.selectedMaterial ? [this.selectedMaterial] : [];
          return Promise.resolve();
        }
        const params = {
          SQL: `SELECT DISTINCT a.id FROM tb_standard_assembly_product a WHERE a.MARK_FOR_DELETE = 0 AND a.REFERRED_ID IN (${this.selectedReferred.join(',')} + ' ')`,
        };
        return new Promise((resolve) => {
          app.utils.ajaxRequest({
            hideMsg: true,
            hideMask: true,
            url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
            params: { functionParam: JSON.stringify(params) },
            callBack: (res) => {
              this.materialIds = res.success && res.rows.length > 0 ? res.rows.map((item) => item.id) : [];
              //this.materialCodes = res.success && res.rows.length > 0 ? res.rows.map((item) => item.code) : [];
              resolve();
            },
          });
        });
      },
      loadMaterialCodesByReferred() {
        if (!this.selectedReferred.length) {
          this.materialIds = this.selectedMaterial ? [this.selectedMaterial] : [];
          return Promise.resolve();
        }
        const params = {
          SQL: `SELECT DISTINCT a.ASSEMBLY_CODE as code FROM tb_standard_assembly_product a WHERE a.MARK_FOR_DELETE = 0 AND a.REFERRED_ID IN (${this.selectedReferred.join(',')} + ' ')`,
        };
        return new Promise((resolve) => {
          app.utils.ajaxRequest({
            hideMsg: true,
            hideMask: true,
            url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
            params: { functionParam: JSON.stringify(params) },
            callBack: (res) => {
              this.materialCodes = res.success && res.rows.length > 0 ? res.rows.map((item) => item.code) : [];
              resolve();
            },
          });
        });
      },
      loadCodesByMaterialId() {
        if (!this.selectedMaterial.length) {
          return ;
        }
        const params = {
          SQL: `SELECT DISTINCT a.ASSEMBLY_CODE as code FROM tb_standard_assembly_product a WHERE a.MARK_FOR_DELETE = 0 AND a.ID IN (${this.selectedMaterial.join(',') + ' '})`,
        };
        return new Promise((resolve) => {
          app.utils.ajaxRequest({
            hideMsg: true,
            hideMask: true,
            url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
            params: { functionParam: JSON.stringify(params) },
            callBack: (res) => {
              this.materialCodes = res.success && res.rows.length > 0 ? res.rows.map((item) => item.code) : [];
              resolve();
            },
          });
        });
      },
      initYearOptions() {
        const currentDate = new Date();
        const currentYear = currentDate.getFullYear();
        const currentMonth = String(currentDate.getMonth() + 1).padStart(2, '0');
        this.endYear = `${currentYear}-${currentMonth}`;
        const startDate = new Date(currentDate);
        startDate.setFullYear(2023);
        startDate.setMonth(0);
        startDate.setDate(1);
        this.startYear = `${startDate.getFullYear()}-${String(startDate.getMonth() + 1).padStart(2, '0')}`;
      },
      reset() {
        this.searchMaterial = '';
        this.selectedMaterial = '';
        this.selectedReferred = [];
        this.startYear = '';
        this.endYear = '';
        this.search_data();
      },
      customFilter(item, queryText, itemText) {
        const textOne = itemText.toLowerCase();
        const searchText = queryText.toLowerCase();
        return textOne.indexOf(searchText) > -1;
      },
      updateTableData() {
        this.tableItems = this.nameSendList.map((name, index) => ({
          name: name === '无日期' ? '无日期' : name,
          num: this.numList[index],
        }))
        //.filter(item => parseInt(item.name.split('-')[0]) >= 2023); // 过滤2023年以前的数据
      },
      updateTableSendData() {
        this.tableSendItems = this.nameSendList.map((name, index) => ({
          name: name === '无日期' ? '无日期' : name,
          sendnum: this.numSendList[index],
        }))
        //.filter(item => parseInt(item.sendName.split('-')[0]) >= 2023); // 过滤2023年以前的数据
      },
      updateTableRateData() {
        this.tableItemsRate = this.nameSendList.map((name, index) => ({
          name: name === '无日期' ? '无日期' : name,
        //   if(this.numSendList[index]==0){
            faultRate: (this.numList[index] ===null || this.numList[index] ===undefined) ? '0%':(this.numList[index]/this.numSendList[index]*100).toFixed(2)+'%' ,
        //   },
          //this.numList[index]/this.numSendList[index]
          
        }))
        console.log("this.numList[index]="+this.numList[index]);
        console.log("faultRate="+faultRate);
        //.filter(item => parseInt(item.sendName.split('-')[0]) >= 2023); // 过滤2023年以前的数据
      },
      updateTableSumRateData() {
            let numSmallSum = 0; // 初始化总故障数
            let numBigSum = 0;   // 初始化总发货数
  
            for (let numSamll of this.numList) {
                numSmallSum += numSamll; // 累加故障数
            }
  
            for (let numBig of this.numSendList) {
                numBigSum += numBig; // 累加发货数
            }
            if(!(numSmallSum === 0 || numBigSum === 0)) {
                this.sumRate = (numSmallSum / numBigSum * 100).toFixed(2) + '%';
            }else {
                this.sumRate = ' ';
            }
        },
      exportToCSV() {
        try {
          let csvContent = "\ufeff"; // 添加BOM头
          csvContent += "年份,月份,故障数,发货数,故障率\n";
          this.years.forEach((year) => {
            const months = this.getMonths([year]) || [];
            const nums = this.tableItems.filter(item => item.name.startsWith(year)).map(item => item.num);
            const numSend = this.tableSendItems.filter(item => item.name.startsWith(year)).map(item => item.sendnum);
            const rate = this.tableItemsRate.filter(item => item.name.startsWith(year)).map(item => item.faultRate);
            
            months.forEach((month, index) => {
              csvContent += `${year},${month},${nums[index] || ''},${numSend[index] || ''},${rate[index] || ''}\n`;
            });
          });
          let numSmallSum2 = 0; // 初始化总故障数
          let numBigSum2 = 0;   // 初始化总发货数
          let sumRate2 = 0;   // 初始化总发货数
          for (let numSamll of this.numList) {
                numSmallSum2 += numSamll; // 累加故障数
            }
  
            for (let numBig of this.numSendList) {
                numBigSum2 += numBig; // 累加发货数
            }
            if(!(numSmallSum2 === 0 || numBigSum2 === 0)) {
                sumRate2 = (numSmallSum2 / numBigSum2 * 100).toFixed(2) + '%';
            }else {
                this.sumRate2 = '0%';
            }
          
          csvContent += `\n,总故障率,${sumRate2}\n`;
          const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.download = '故障率数据.csv';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        } catch (error) {
          console.error('导出CSV失败:', error);
          app.utils.showMessage('导出CSV失败，请稍后重试');
        }
      },
      exportChart() {
        try {
                // 确保 html2canvas 已正确引入
                if (!html2canvas) {
                console.error('html2canvas 未定义，请确保已正确安装并引入该库');
                app.utils.showMessage('导出图片失败：html2canvas 未定义');
                return;
                }

                // 检查表格元素是否存在
                const tableElement = this.$refs.table?.$el;
                if (!tableElement) {
                console.error('表格元素未找到，请检查 ref="table" 是否正确绑定');
                app.utils.showMessage('导出图片失败：表格元素未找到');
                return;
                }

                // 使用 html2canvas 将表格转换为图片
                html2canvas(tableElement, {
                scale: 2, // 提高分辨率
                backgroundColor: '#ffffff', // 设置背景颜色
                useCORS: true, // 允许跨域资源（如图片）
                }).then(canvas => {
                // 将 canvas 转换为图片数据 URL
                const image = canvas.toDataURL('image/png');

                // 创建下载链接
                const link = document.createElement('a');
                link.href = image;
                link.download = '故障率图表.png'; // 下载文件名
                document.body.appendChild(link);
                link.click(); // 触发下载
                document.body.removeChild(link); // 清理 DOM
                }).catch(error => {
                console.error('html2canvas 转换失败:', error);
                app.utils.showMessage('导出图片失败：无法生成图片');
                });
            } catch (error) {
                console.error('导出图片失败:', error);
                app.utils.showMessage('导出图片失败，请稍后重试');
            }
},
      // 获取年份跨度（用于 colspan）
      getYearSpan(year) {
        return this.tableItems.filter(item => item.name.startsWith(year)).length;
      },
      // 获取所有月份数据
      getMonths(years) {
        const months = [];
        years.forEach(year => {
          const yearMonths = this.tableItems
            .filter(item => item.name.startsWith(year))
            .map(item => item.name.split('-')[1]); // 提取月份
          months.push(...yearMonths);
        });
        
        return months;
      },
    },
    watch: {
      selectedMaterial() {
        if (this.selectedMaterial) {
          this.selectedReferred = [];
          this.materialIds = [this.selectedMaterial];
          this.search_data();
          this.loadCodesByMaterialId().then(() => {
                  if (this.materialCodes.length > 0) this.search_data_sendout();
                });
        }
      },
      selectedReferred() {
        this.selectedReferredById();
        this.selectedReferredByCode();
        setTimeout(()=>{
          this.updateTableRateData()},1000);
        setTimeout(()=>{
          this.updateTableSumRateData()},1000);
      },
  
      startYear() {
        if (this.materialIds.length > 0) this.search_data();
        if (this.materialIds.length > 0) this.search_data_sendout();
        setTimeout(()=>{
          this.updateTableRateData()},500);
        setTimeout(()=>{
          this.updateTableSumRateData()},500);
      },
      endYear() {
        if (this.materialIds.length > 0) this.search_data();
        if (this.materialIds.length > 0) this.search_data_sendout();
        setTimeout(()=>{
          this.updateTableRateData()},500);
        setTimeout(()=>{
          this.updateTableSumRateData()},500);
      },
    },
    created() {
      this.initYearOptions();
      this.loadMaterialData();
      this.loadReferredData();
      setTimeout(() => this.search_data(), 1500);
    },
  };
  </script>